package com.security.security.provider;

import com.security.security.authention.SmsAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * @作者: 林江
 * @创建时间: 2024/1/3
 * @功能: 短信认证
 */
public class SmsAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    /**
     * 进行认证
     * Authentication --》 SmsAuthenticationToken
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;

        String mobile = (String) authenticationToken.getPrincipal();
        UserDetails userDetails = null;
        try {
            userDetails = userDetailsService.loadUserByUsername(mobile);
        } catch (UsernameNotFoundException ex) {
            throw new BadCredentialsException("Bad credentials", ex);
        }

        // 校验短信验证码
        checkSmsCode(authentication.getCredentials(), authenticationToken.getRequest());

        // 此时鉴权成功后，应当重新 new 一个拥有鉴权的 authenticationResult 返回
        SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    private void checkSmsCode(Object credentials, HttpServletRequest request) {
        // 从session中获取验证码 或者 TODO 从redis中获取验证码
//        if (credentials == null) {
//            throw new BadCredentialsException("验证码为空");
//        }
//
//        Object smsCode = request.getSession().getAttribute("smsCode");
//        if (smsCode == null &&!credentials.toString().equals(smsCode.toString())) {
//            throw new BadCredentialsException("验证码错误");
//        }
    }

    /**
     * 表示这个认证是否支持authentication
     *
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return (SmsAuthenticationToken.class.isAssignableFrom(authentication));
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }
}
